package com.ddlaw.utils;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import com.ddlaw.enums.UploadEnum;



public class Upload {
	private static final Logger logger = LoggerFactory.getLogger(Upload.class);
	
	private static String uploadPath = null;// 上传文件的目录
	private static File uploadFile = null;
	static{
        uploadPath = UploadEnum.FILEPATH.getValue();
        uploadFile = new File(uploadPath);
        if (!uploadFile.exists()) {
            uploadFile.mkdirs();
        }
	}
	/**
	 * 上传文件
	 * @param file 文件
	 * @param request
	 * @return
	 */
	public static String uploadFile(MultipartFile file,HttpServletRequest request,String type,String fileName) {
		String URL = "";
		String UUIDName = "";
		if(!file.isEmpty()){
			//得到上传时的文件名
		    String filename = file.getOriginalFilename();
		    if ("".equals(fileName)) {
		    	//更改文件名
		    	UUIDName = UUID.randomUUID().toString()+filename.substring(filename.lastIndexOf("."));
		    }else{
		    	//指定名字
		    	UUIDName = fileName + filename.substring(filename.lastIndexOf("."));
		    }
		    //文件保存至服务器
		    try {  
		      //文件保存至临时路径
		      FileUtils.writeByteArrayToFile(new File(uploadPath,UUIDName), file.getBytes());
		      URL = type + UUIDName;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		    logger.info("File Upload Complet!");
		}    
				return URL;
	}
}
